import * as tf from "@tensorflow/tfjs";
import * as tfvis from "@tensorflow/tfjs-vis";
/**
 * 
 * 
 * */
(async () => {
  // x 轴输入
  let xs = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
  // y轴输出
  let ys = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23];

  // 初始化模型
  let model = tf.sequential();
  // 添加层，添加点乘层
  let layer1 = model.add(
    tf.layers.dense({
      units: 1, // 神经元个数
      inputShape: [1],
    })
  );
  let m = model.compile({
    loss: tf.losses.meanSquaredError, // 均方误差
    optimizer: tf.train.sgd(0.002), //
    // optimizer: tf.train.adam(),
  });
  // 渲染图表
  tfvis.render.scatterplot(
    {
      name: "线性回归体验",
    },
    {
      values: xs.map((x, i) => ({ x, y: ys[i] })),
    }
  );

  // 输入值
  const inputs = tf.tensor(xs);
  // 正确值
  const labels = tf.tensor(ys);
  await model.fit(inputs, labels, {
    // 学习样本数量
    batchSize: 6,
    // 迭代多少次训练次数
    epochs: 100,
    // 调用
    callbacks: tfvis.show.fitCallbacks(
        { name: "训练" },
        // 度量单位可视化单位
        ["loss"]),
  });
  // 预测 输入tensor
  const output = model.predict(tf.tensor([100]));
  // 输出
  console.log(output.dataSync());

})();


